package cn.edu.ctbu.dp01.service.impl;

import cn.edu.ctbu.dp01.entity.Student;
import cn.edu.ctbu.dp01.repository.StudentRepository;
import cn.edu.ctbu.dp01.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import jakarta.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Override
    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    @Override
    public Student save(Student student) {
        return studentRepository.save(student);
    }

    @Override
    public void deleteById(Integer id) {
        studentRepository.deleteById(id);
    }

    @Override
    public Student findById(Integer id) {
        return studentRepository.findById(id).orElse(null);
    }

    @Override
    public Page<Student> findStudentsWithFilters(String name, String sno, Integer age, Integer sex, Pageable pageable) {
        Specification<Student> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            
            if (name != null && !name.trim().isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
            }
            
            if (sno != null && !sno.trim().isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("sno"), "%" + sno + "%"));
            }
            
            if (age != null) {
                predicates.add(criteriaBuilder.equal(root.get("age"), age));
            }
            
            if (sex != null) {
                predicates.add(criteriaBuilder.equal(root.get("sex"), sex));
            }
            
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        
        return studentRepository.findAll(spec, pageable);
    }
}